package com.techstar.api.service;

import java.io.FileReader;
import java.io.Reader;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.data.jpa.repository.JpaRepository;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techstar.api.util.GateWayApiProperties;
import com.techstar.api.util.TrafficApiProperties;
import com.techstar.common.jackson.JacksonMapper;
import com.techstar.common.pojo.InterfaceType;
import com.techstar.common.utils.InterfaceUtils;

import lombok.extern.slf4j.Slf4j;
/**
 * 
 * @author EinIce
 * @description 本地测试
 * @date 2021年9月9日
 */
@Slf4j
public class ParentLocalService<T> {
	@SuppressWarnings("rawtypes")
	protected JpaRepository beanRepos;
	
	protected GateWayApiProperties gateWayApiProperties;
	
	protected TrafficApiProperties trafficApiProperties;
	
	protected InterfaceType interfaceType;
	
	protected static final ObjectMapper objectMapper = JacksonMapper.instance.objectMapper;
	
	@SuppressWarnings("unchecked")
	public void sendHttp(TypeReference<List<T>> typeReference){
		if(gateWayApiProperties.testMode==true&&!"test".equals(trafficApiProperties.able)
				||"disable".equals(trafficApiProperties.able)) {
			log.info("DistrictCongestTrendService out");
			return;
		}
		try {
			Reader reader = new FileReader("D:\\工作\\恒泰\\交委\\数据样例\\测试数据.json");
			int ch = reader.read();
			StringBuffer buffer = new StringBuffer();
			while (ch != -1) { // 读取成功
				buffer.append((char) ch);
				ch = reader.read();
			}
			reader.close();
			String result = buffer.toString();
            log.info(result);
            JsonNode jsonNode = objectMapper.readTree(result.toString()).get("data");
            try {
//            	interfaceType.setApiUrl(httpGet.toString());
            	interfaceType.setApiUrl("test");
            	interfaceType.setClassName(this.getClass().getSimpleName());
            	InterfaceUtils.filtrateDate(interfaceType, DateTime.now(), jsonNode);
            } catch (Exception e) {
            	e.printStackTrace();
            	log.error("接口记录失败-"+this.getClass().getSimpleName()+":"+e.getMessage());
            }
            if(jsonNode==null)return;
			List<T> list = objectMapper.readValue(jsonNode.toString(),typeReference);
			System.out.println(list.toString());
			beanRepos.saveAll(list);
        }catch (Exception e) {
        	log.error(e.getMessage());
        	e.printStackTrace();
        	return;
		}
	}
}
